import { defineStore } from 'pinia'
import { reqLogin } from '@/api/user'

//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import type {
  loginFormData,
  loginResponseData,
} from '@/api/user/type'
//引入路由(常量路由)
import { constantRoute } from '@/router/routes'

//创建用户小仓库
const useUserStore = defineStore('user', {
  //小仓库存储数据地方
  state: () => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      username: '',
      avatar: '',
      menuRoutes: constantRoute, //仓库存储生成菜单需要数组(路由)
    }
  },

  actions: {
    async userLogin(data: loginFormData) {
      //登录请求
      const result: loginResponseData = await reqLogin(data)
      if (result.code == 200) {
        //由于pinia|vuex存储数据其实利用js对象
        this.token = result.data as string
        //本地存储持久化存储一份
        SET_TOKEN(result.data as string)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
  },

  getters: {},

})

export default useUserStore
